<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="年-月" prop="date">
              <el-date-picker clearable v-model="queryParams.date" type="month" value-format="YYYY-MM" placeholder="请选择日期" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table border v-loading="loading" :data="allocationList" class="enhanced-table">
        <el-table-column label="主键id" align="center" prop="id" v-if="false" />
        <!--        <el-table-column label="编号" align="center" prop="num" width="80" />-->
        <el-table-column label="预算科目编码" align="center" prop="subjectCode" width="120" />
        <el-table-column label="预算科目名称" align="center" prop="subjectName" width="120" />
        <el-table-column label="会计科目编码" align="center" prop="accountSubjectCode" width="180" />
        <el-table-column label="会计科目名称" align="center" prop="accountSubjectName" width="180" />
        <el-table-column label="日期" align="center" prop="date" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="凭证号" align="center" prop="voucherNum" />
        <el-table-column label="部门编码" align="center" prop="deptCode" width="150" />
        <el-table-column label="部门名称" align="center" prop="deptName" width="150" />
        <el-table-column label="摘要" align="center" prop="summary" show-overflow-tooltip width="300" />
        <el-table-column label="金额" align="center" prop="md" width="150" />
        <el-table-column label="院区" align="center" prop="yardName" />
        <el-table-column label="分配状态" align="center" prop="state" fixed="right" width="100">
          <template #default="scope">
            <dict-tag :options="allot_state" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="140">
          <template #default="scope">
            <el-button
              type="primary"
              icon="Right"
              @click="handleAllocation(scope.row, 0)"
              v-hasPermi="['collect:allocation:allot']"
              v-if="scope.row.state === '0'"
              class="btn"
              plain
              >分配
            </el-button>
            <el-button
              type="danger"
              icon="Back"
              @click="handleAllocation(scope.row, 1)"
              v-hasPermi="['collect:allocation:back']"
              v-else-if="scope.row.state === '1'"
              class="btn"
              plain
              >撤销
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改数据分配（费用类数据）对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="allocationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预算科目 ">
          <el-tree-select
            v-model="form.subjectCode"
            :data="subjectList"
            :props="{ value: 'subjectCode', label: 'subjectName', children: 'children', disabled: 'disabled' }"
            value-key="subjectCode"
            placeholder="请选择预算科目"
            check-strictly
            @node-click="handleNodeClick"
            filterable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Allocation" lang="ts">
import { listAllocation } from '@/api/collect/allocation';
import { AllocationForm, AllocationQuery, AllocationVO } from '@/api/collect/allocation/types';
import { parseTime } from '@/utils/ruoyi';
import { BudgetSubjectQuery, BudgetSubjectVO } from '@/api/budget/budgetSubject/types';
import { listBudgetSubject } from '@/api/budget/budgetSubject';
import useDate from '@/hooks/useDate';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { allot_state } = toRefs<any>(proxy?.useDict('allot_state'));

const allocationList = ref<AllocationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);

const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const allocationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const queryParams = ref<AllocationQuery>({
  pageNum: 1,
  pageSize: 10,
  date: useDate.getPreviousMonth()
});

const initFormData: AllocationForm = {
  id: undefined,
  subjectCode: undefined,
  isEnd: false
};
const form = ref<AllocationForm>({ ...initFormData });

const rules = ref({
  subjectCode: [{ required: true, message: '预算科目不能为空', trigger: 'change' }]
});
/** 查询数据分配（费用类数据）列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAllocation(queryParams.value);
  allocationList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value.id = undefined;
  form.value.isEnd = undefined;
  form.value.subjectCode = undefined;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
const subjectList = ref<BudgetSubjectVO[]>([]);

/** 分配/撤销按钮操作 */
const handleAllocation = async (row: AllocationVO, type: number) => {
  buttonLoading.value = false;
  reset();
  if (type === 0) {
    //分配
    initFormData.id = row.id;
    dialog.visible = true;
    dialog.title = '分配预算科目';
    await getTreeSelect();
  } else if (type === 1) {
    //撤销
    proxy.$modal.confirm('是否确认撤销分配?').then(() => {
      // withdraw(row.id).then(() => {
      //   proxy.$modal.msgSuccess('操作成功');
      //   getList();
      // });
    });
  }
};
/** 科目树形下拉框*/
const listParams = ref<BudgetSubjectQuery>({
  state: '0', //正常
  label: 2
});
//树形结构列表数据
const getTreeSelect = async () => {
  subjectList.value = [];
  const res = await listBudgetSubject(listParams.value);
  subjectList.value = res.data;
};

const handleNodeClick = (data: BudgetSubjectVO) => {
  console.log(data);
  initFormData.subjectCode = data.subjectCode;
  // initFormData.isEnd = data.isEnd;
};

/** 提交按钮 */
const submitForm = async () => {
  console.log(initFormData);
  buttonLoading.value = true;
  // await allocation(initFormData).then(() => {
  //   proxy.$modal.msgSuccess('分配成功');
  // });
  dialog.visible = false;
  await getList();
  buttonLoading.value = false;
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.btn {
  width: 70px;
  height: 25px;
}
</style>
